# encoding=utf-8

"""注意此代码建立在明星设备使用了ROI切割多余像素的基础上
"""
import time
import math
import cv2
import numpy as np
import skimage


def time_wrapper(f, *args, **kwargs):
    t1 = time.perf_counter()
    res = f(*args, **kwargs)
    t2 = time.perf_counter()
    print("{}, time: {}s".format(f, t2 - t1))
    return res


def find_max_crop(image_src: str):
    # 读取图像
    image = cv2.imread(image_src)  # 假设图像为彩色图

    # 灰度化处理
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 二值化处理
    _, binary_image = cv2.threshold(gray_image, 7, 255, cv2.THRESH_BINARY)

    # 边框
    x, y, w, h = cv2.boundingRect(binary_image)

    # 边框最大内接圆
    center = (w // 2), (h // 2)
    radius = min(center)

    # 内接圆转box
    y = y + center[1] - radius
    x = x + center[0] - radius
    copy_image = image[y: y + 2 * radius, x: x + 2 * radius]

    # 生成mask
    mask = np.zeros_like(copy_image)
    cv2.circle(mask, (radius, radius), radius, (1, 1, 1), -1)

    # 曝光
    gen_mask = copy_image * mask
    img = cv2.addWeighted(gen_mask, 4, cv2.GaussianBlur(gen_mask, (0, 0), 30), -4, 128)
    return img, gen_mask, copy_image


def preprocess(image_src: str):
    # load
    image = cv2.imread(image_src)

    # binary
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, binary_image = cv2.threshold(gray_image, 7, 255, cv2.THRESH_BINARY)

    # cal roi
    x, y, w, h = cv2.boundingRect(binary_image)
    center = (w // 2), (h // 2)
    radius = min(center)
    y = y + center[1] - radius
    x = x + center[0] - radius
    copy_image = image[y: y + 2 * radius, x: x + 2 * radius]

    # gen mask
    mask = np.zeros_like(copy_image)
    cv2.circle(mask, (radius, radius), radius, (1, 1, 1), -1)

    # exposure
    gen_mask = copy_image * mask
    t1 = time.perf_counter()
    blur_out = cv2.GaussianBlur(gen_mask, (0, 0), 30)
    # blur_out = skimage.filters.gaussian(gen_mask, sigma=10, truncate=0, channel_axis=-1).astype(np.uint8)
    exposure = cv2.addWeighted(gen_mask, 4, blur_out, -4, 128)
    t2 = time.perf_counter()
    print("time", t2 - t1)
    return cv2.resize(cv2.cvtColor(exposure, cv2.COLOR_BGR2RGB), (224, 224), interpolation=cv2.INTER_LINEAR)


if __name__ == '__main__':
    image_src = ["t1.jpeg", "t2.jpeg"]
    # for e_s in image_src:
    #     img, gen_mask, copy_image = time_wrapper(find_max_crop, e_s)
    #     cv2.imwrite(e_s.replace(".jpeg", "_opti.png"), img)
    #     cv2.imwrite(e_s.replace(".jpeg", "_opti_debug_1.png"), gen_mask)
    #     cv2.imwrite(e_s.replace(".jpeg", "_opti_debug_2.png"), copy_image)
    for e_s in image_src:
        img = time_wrapper(preprocess, e_s)
        cv2.imwrite(e_s.replace(".jpeg", "_opti_preprocess.png"), img)

